package com.sqpoll.android;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.actionbarsherlock.app.SherlockFragment;
import com.facebook.LoggingBehavior;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.Settings;

/**
 * Fragment for login via Facebook or Twitter authentication.
 * 
 * @author Honggyun Bae, Younggue Bae
 */
public class LoginFragment extends SherlockFragment {
	private static final String TAG = "LoginFragment";

	private Button mButtonFacebookLogin;

	private Session.StatusCallback statusCallback = new SessionStatusCallback();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_login, container, false);

		mButtonFacebookLogin = (Button) view.findViewById(R.id.button_facebook_login);
		mButtonFacebookLogin.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				onClickLogin();
			}
		});

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session session = Session.getActiveSession();
		if (session == null) {
			if (savedInstanceState != null) {
				Log.d(TAG, "*savedInstanceState != null");
				session = Session.restoreSession(getActivity(), null, statusCallback, savedInstanceState);
			}
			if (session == null) {
				Log.d(TAG, "*session == null");
				session = new Session(getActivity());
			}
			Session.setActiveSession(session);
			if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
				Log.d(TAG, "*session.getState().equals(SessionState.CREATED_TOKEN_LOADED)");
				session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
			}
		} else {
			Log.d(TAG, "session != null");
			updateView();
		}

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();
		Session.getActiveSession().addCallback(statusCallback);
	}

	@Override
	public void onStop() {
		super.onStop();
		Session.getActiveSession().removeCallback(statusCallback);
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(getActivity(), requestCode, resultCode, data);
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Session session = Session.getActiveSession();
		Session.saveSession(session, outState);
	}

	private void onClickLogin() {
		Session session = Session.getActiveSession();
		Log.d(TAG, "session == " + session);
		if (!session.isOpened() && !session.isClosed()) {
			Log.d(TAG, "!session.isOpened() && !session.isClosed()");
			session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));
		} else {
			Log.d(TAG, "else --> !session.isOpened() && !session.isClosed()");
			Session.openActiveSession(getActivity(), this, true, statusCallback);
		}
	}

	@SuppressWarnings("unused")
	private void onClickLogout() {
		Session session = Session.getActiveSession();
		if (!session.isClosed()) {
			session.closeAndClearTokenInformation();
		}
	}

	private void updateView() {
		Session session = Session.getActiveSession();
		Log.d(TAG, "updateView");
		if (session.isOpened()) {
			Log.d(TAG, "session.isOpened()");
			startActivity(new Intent(getActivity(), MainActivity.class));
			getActivity().finish();
		}
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (state.isOpened()) {
			Log.i(TAG, "Logged in...");
			startActivity(new Intent(getActivity(), MainActivity.class));
			getActivity().finish();
		} else if (state.isClosed()) {
			Log.i(TAG, "Logged out...");
		}
	}

	private class SessionStatusCallback implements Session.StatusCallback {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	}

}
